import { getToken } from './auth';
import { useStore } from '@/store';
import router from '@/router';
import { isEmpty } from './index';
import { createDiscreteApi } from 'naive-ui';

const { message } = createDiscreteApi(['message']);

/**
 * ajax请求数据封装
 * @param obj - options
 * @contentType - 请求头
 * @method - 请求方法 ['GET', 'POST']
 * @url - 地址
 * @params - 数据
 * @token - token验证
 *
 * 例：
 * Xsync({
        method: 'GET',
        url: './lib/test.json',
        params: {id: 123},
        token: 'token-token'
    }).then(res => {
        console.log('then:', res);
    }).catch(err => {
        console.log('catch:', err);
    });
 */
/**
 * 格式化url参数
 * @param url
 * @param params
 * @returns {string|*}
 */
const formatUrl = (url, params) => {
    if (isEmpty(params)) return url;
    let param = '';
    const keys = Object.keys(params);
    const lastIndex = keys.length - 1;
    keys.forEach((key, i) => {
        param += `${key}=${encodeURIComponent(params[key])}${
            lastIndex === i ? '' : '&'
        }`;
    });
    if (param) return `${url}?${param}`;
    return url;
};

async function Fetch({
    method = 'GET',
    url = '',
    contentType = 'application/json',
    params = {},
    token = '',
    resType = 'json'
}) {
    const mainStore = useStore();
    const headers = {
        'Content-Type': contentType
    };
    if (token) {
        headers.token = token;
    } else {
        const t = getToken();
        if (t) headers.token = t;
    }
    // 对header需要的参数做统一处理
    if (mainStore) {
        const { groupCode, projectId } = mainStore;
        // console.log(userInfo)
        headers['project-id'] = projectId;
        headers['group-code'] = groupCode;
    }

    try {
        const init = {
            method,
            headers
        };
        let reqUrl = url;
        if (method.toUpperCase() === 'POST' || method.toUpperCase() === 'PUT') {
            init.body = JSON.stringify(params);
        } else {
            reqUrl = formatUrl(url, params);
        }
        const response = await window.fetch(reqUrl, init);
        const { status } = response;
        let data;
        try {
            data = await response[resType]();
        } catch (e) {
            if (status === 200) data = {};
            else data = e;
        }
        return { status, data };
    } catch (e) {
        console.error('request failed!', e);
        return { message: 'request failed!' };
    }
}

export default async options => {
    const result = await Fetch(options);
    const { status, data } = result;
    return new Promise((resolve, reject) => {
        // 未登陆 / 登陆凭证过期
        if (status === 401 || status === 403) {
            // token失效
            message.error(data.message);
            setTimeout(() => {
                router.push({ name: 'login' });
            }, 800);
        } else if (status === 200) {
            resolve(data);
        } else {
            message.error(data.message || status);
            reject(data);
        }
    });
};
